package com.itheima.w_util;

import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.Yaml;   
import org.yaml.snakeyaml.nodes.Tag;   
import org.yaml.snakeyaml.representer.Representer;
   
import java.io.*;   
import java.util.*;
   
/**
   * YAML文件操作工具类
   */   
public class YmlUtils {
    
    private static final Yaml yaml;
    
    static {
        // 初始化YAML实例，配置输出格式
        DumperOptions options = new DumperOptions();
        options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); // 块状格式
        options.setPrettyFlow(true); // 美化输出
        options.setIndent(2); // 缩进2个空格
        options.setDefaultScalarStyle(DumperOptions.ScalarStyle.PLAIN);
        
        Representer representer = new Representer();
        representer.addClassTag(Map.class, Tag.MAP); // 避免自动添加类型标记
        
        yaml = new Yaml(representer, options);
    }
    
    /**
     * 创建空YAML配置
     */
    public static Map<String, Object> createEmptyConfig() {
        return new LinkedHashMap<>(); // 保持插入顺序
    }
    
    /**
     * 添加基础配置项
     * @param config 目标配置
     * @param key 键
     * @param value 值（支持String/Number/Boolean/List/Map等）
     */
    public static void addConfigItem(Map<String, Object> config, String key, Object value) {
        config.put(key, value);
    }
    
    /**
     * 添加嵌套配置
     * @param parentConfig 父配置
     * @param path 用点分隔的路径（如：server.port）
     * @param value 值
     */
    public static void addNestedConfig(Map<String, Object> parentConfig, String path, Object value) {
        value=getValue(value);
        String[] keys = path.split("\\.");
        Map<String, Object> current = parentConfig;
        
        for (int i = 0; i < keys.length - 1; i++) {
            String key = keys[i];
            current = (Map<String, Object>) current.computeIfAbsent(key, k -> new LinkedHashMap<>());
        }
        
        current.put(keys[keys.length - 1], value);
    }
    
    /**
     * 将配置写入YAML文件
     * @param config 配置数据
     * @param filePath 文件路径
     */
    public static void writeToFile(Map<String, Object> config, String filePath)  {
        try (FileWriter writer = new FileWriter(filePath)) {
            yaml.dump(config, writer);
        }catch (Exception e) {

        }
    }
    
    /**
     * 从文件读取YAML配置
     * @param filePath 文件路径
     * @return 配置数据
     */
    public static Map<String, Object> readFromFile(String filePath) throws IOException {
        try (FileReader reader = new FileReader(filePath)) {
            return yaml.load(reader);
        }
    }

    private static Object getValue(Object value) {
        String valueStr = StrUtil.toString(value);
        try {
            return Long.parseLong(valueStr);
        } catch (NumberFormatException e) {
            return valueStr;
        }
    }

}   
